package com.njlime.cms.controller.sys;

import com.mchange.util.DuplicateElementException;
import com.njlime.cms.entities.Channel;
import com.njlime.cms.entities.MaterialsImage;
import com.njlime.cms.entities.MaterialsImageGroup;
import com.njlime.cms.service.sys.ChannelService;
import com.njlime.cms.service.sys.MaterialImageGroupService;
import com.njlime.cms.service.sys.MaterialImageService;
import com.njlime.cms.util.UrlUtil;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.sdk.wechat.user.UserLable;
import com.njlime.member.entiies.TMemberGroup;
import com.njlime.sys.security.util.UserUtils;
import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 素材管理-图片
 * Created by Dean on 2017/8/10.
 */
@Controller
@RequestMapping(value = "/cms/meterial")
public class MaterialImageController extends BaseController {

    @Resource
    MaterialImageService materialImageService;

    @Resource
    MaterialImageGroupService materialImageGroupService;
    /**
     * 图片素材入口页面
     *
     * @return
     */
    @RequestMapping(value = "/toImageList" )
    public ModelAndView roleManage(HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("/sys/content/meterial/image");

        int unitId = UserUtils.getUser().getRootUnit().getId();

        modelAndView.addObject("groupList",materialImageGroupService.list(unitId));

        return modelAndView;
    }

    /**
     * 图片新增
     * @param request
     * @param info
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addImage")
    public String addImage(HttpServletRequest request,MaterialsImage info ){
        try {
           int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setUnit_id(unitId);
            info.setDel(0);

            info.setCreate_time(new Date().getTime()/1000 );
            materialImageService.save(info);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error(e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 查询图片素材
     *
     * @param request
     * @param groupId 组id
     * @return
     */
    @RequestMapping(value = "getImageList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getImageList(PageBean pageBean, HttpServletRequest request,int groupId,String name ) {
        try {
         int unitId = UserUtils.getUser().getRootUnit().getId();

            return toJsonListData(materialImageService.getImageList(pageBean ,unitId,groupId,name));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除图片素材
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delImage", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String delImage(String id, HttpServletRequest request) {
        try {

          int unitId = UserUtils.getUser().getRootUnit().getId();

            materialImageService.delImage( id,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 查询图片素材分组
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getImageGroupList", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String getImageGroupList(PageBean pageBean, HttpServletRequest request ) {
        try {

           int unitId = UserUtils.getUser().getRootUnit().getId();

            Map map = materialImageGroupService.getSumMember(unitId);
            List<MaterialsImageGroup> list = materialImageGroupService.list( unitId);
            Map resMap = new HashMap();

            resMap.put("sumMap",map);
            resMap.put("list",list);

            return toJsonListData(resMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 分组新增
     * @param request
     * @param info
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addImageGroup")
    public String addGroup(HttpServletRequest request,MaterialsImageGroup info ){
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            info.setUnit_id(unitId);
            info.setCount(0);
            info.setDel(0);
            info.setCreate_time(new Date() );
            materialImageGroupService.add(info);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 修改图片分组
     * @param ids
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "editImageGroup", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String editImageGroup(String ids,int groupId, HttpServletRequest request, HttpServletResponse response) {
        try {
          int unitId = UserUtils.getUser().getRootUnit().getId();

            materialImageService.editImageGroup(ids,groupId,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 修改分组
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "editGroup", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String editGroup(String id,String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            materialImageService.editGroup(id,name,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 删除分组
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "deleteGroup", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String deleteGroup(String id,  HttpServletRequest request, HttpServletResponse response) {
        try {
            int unitId = UserUtils.getUser().getRootUnit().getId();

            materialImageService.deleteGroup(id,unitId);
            return toJsonSuccessData();
        } catch (Exception e) {
            logger.error("", e);
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    @RequestMapping(value = "downloadImage")
    @ResponseBody
    public void downloadImage(HttpServletResponse response, String ids){
        try {
            String filename = new String((System.currentTimeMillis() + ".zip").getBytes("UTF-8"), "ISO8859-1");//控制文件名编码
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            String[] idArr = ids.split(",");
            for (int i = 0; i < idArr.length; i++) {
                MaterialsImage image = materialImageService.findOne(Integer.valueOf(idArr[i]));
                zos.putNextEntry(new ZipEntry("(" + (i+1) + ") " + image.getTitle() + image.getPath().substring(image.getPath().lastIndexOf("."))));
                byte[] bytes = UrlUtil.getImageFromNetByUrl(image.getPath());
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
            }
            zos.close();
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + filename);// 设置文件名
            OutputStream os = response.getOutputStream();
            os.write(bos.toByteArray());
            os.close();
        } catch (Exception ex) {
            logger.error("Exception", ex);
        }
    }

}
